package com.lianjia.sh.tools.msg.v1.sender.impl;

import com.alibaba.fastjson.JSONObject;
import com.dooioo.se.client.RestClient;
import com.lianjia.sh.tools.msg.v1.model.*;
import com.lianjia.sh.tools.msg.v1.sender.SmsSender;
import org.springframework.http.HttpMethod;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yangsp1 on 16/6/24.
 */
public class SmsSenderImpl implements SmsSender {
    //短信接口url
    String smsUrl;

    public boolean isMatch(Msg msg){
        return  msg instanceof SmsMsg;
    }

    @Override
    public boolean send(Msg msg) {
        Assert.notNull(msg);
        Assert.isTrue(isMatch(msg));
        if(msg instanceof SmsMsg){
            return send((SmsMsg) msg);
        }
        return false;
    }

    public boolean send(SmsMsg smsMsg){
        System.out.println("发送短信：" + smsMsg.getMsg());
        Map<String, String> params = new HashMap<>();
        params.put("phone",smsMsg.getPhone());
        params.put("msg", smsMsg.getMsg());
        params.put("project", smsMsg.getProject());
        return send(params);
    }

    private boolean send(Map<String, String> params){
        JSONObject result = null;
        try {
            result = RestClient.exchange(getSmsUrl(), HttpMethod.POST,JSONObject.class,params);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public String getSmsUrl() {
        return smsUrl;
    }

    public void setSmsUrl(String smsUrl) {
        this.smsUrl = smsUrl;
    }
}
